<template>
  <div>
    <div class="query-form">
      <a-form ref="queryFormRef" :model="queryForm" layout="inline" @submit="handleQuery">
        <a-form-item field="roleName" label="角色名称">
          <a-input v-model="queryForm.roleName" placeholder="请输入角色名称" />
        </a-form-item>
        <a-form-item class="operate">
          <a-button type="primary" html-type="submit">查询</a-button>
          <a-button @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </div>
    <div class="operate-wrapper">
      <a-button type="primary" status="success" @click="openAddModal">添加</a-button>
    </div>
    <a-table
      :data="tableData"
      :pagination="paginationProps"
      @page-change="handlePageChange"
      @page-size-change="handleSizeChange"
    >
      <template #columns>
        <a-table-column title="角色名称" data-index="roleName"></a-table-column>
        <a-table-column title="备注" data-index="remark"></a-table-column>
        <!-- <a-table-column title="权限列表" data-index=""></a-table-column> -->
        <a-table-column title="创建时间" data-index="createTime"></a-table-column>
        <a-table-column title="更新时间" data-index="updateTime"></a-table-column>
        <a-table-column title="操作">
          <template #cell="{ record }">
            <a-button type="text" @click="openUptModal(record)">编辑</a-button>
            <a-button type="text" @click="openPermissionModal(record)">设置权限</a-button>
            <a-button type="text" @click="handleDelete(record)">删除</a-button>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <!-- 添加/编辑弹窗 -->
    <a-modal :visible="modalVisible" title="添加/编辑角色" @ok="handleAddOrUpt" @cancel="closeAddModal">
      <a-form ref="modalFormRef" :model="modalForm" :rules="modalFormRules">
        <a-form-item field="roleName" label="角色名称">
          <a-input v-model="modalForm.roleName" />
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-input v-model="modalForm.remark" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 设置权限弹窗 -->
    <a-modal
      :visible="permissionsModalVisible"
      title="设置权限"
      @ok="handlePermissions"
      @cancel="closePermissonsModal"
    >
      <a-tree
        ref="treeRef"
        :checkable="true"
        v-model:checked-keys="checkedKeys"
        :fieldNames="{
          key: '_id',
          title: 'menuName'
        }"
        :data="treeData"
      />
    </a-modal>
  </div>
</template>

<script>
import {
  roleAdd,
  roleDelete,
  roleUpdate,
  roleList,
  rolePermission
} from "@/api/role/index.js";
import { menuList } from "@/api/menu/index.js";
import { reactive, ref, onMounted } from "vue";
import { Modal } from "@arco-design/web-vue";

export default {
  setup() {
    onMounted(() => {
      getRoleList();
      getMenuList();
    });
    // 条件查询表单
    const queryForm = reactive({
      roleName: ""
    });
    const queryFormRef = ref(null);
    const handleQuery = values => {
      console.log("values", values);
      getRoleList();
    };
    const handleReset = () => {
      queryFormRef.value.resetFields();
      getRoleList();
    };
    // 添加/编辑角色弹窗
    const modalVisible = ref(false);
    const modalFormRef = ref(null);
    let modalForm = reactive({
      roleName: "",
      remark: ""
    });
    const modalFormRules = reactive({
      roleName: { required: true, message: "roleName is required" }
    });
    const action = ref("add");
    const closeAddModal = () => {
      modalVisible.value = false;
      modalFormRef.value.resetFields();
    };
    // 添加
    const openAddModal = () => {
      action.value = "add";
      modalFormRef.value.resetFields();
      modalVisible.value = true;
    };
    // 更新
    const openUptModal = record => {
      action.value = "upt";
      Object.assign(modalForm, record);
      modalVisible.value = true;
    };
    const handleAddOrUpt = () => {
      modalFormRef.value.validate(async (errors, Record) => {
        if (errors) return;
        if (action.value == "add") {
          const { data } = await roleAdd(modalForm);
          console.log("data", data);
        }
        if (action.value == "upt") {
          const { data } = await roleUpdate(modalForm);
          console.log("data", data);
        }
        getRoleList();
        modalVisible.value = false;
      });
    };

    // 表格数据
    let tableData = ref([]);
    const pager = reactive({
      pageNum: 1,
      pageSize: 10
    });
    const getRoleList = async () => {
      let params = { ...queryForm, ...pager };
      const { data } = await roleList(params);
      tableData.value = data.data.list;
      paginationProps.total = data.data.page.total;
    };
    // 分页
    const paginationProps = reactive({
      total: 0,
      current: 1,
      pageSize: 10,
      showTotal: true,
      showPageSize: true
    });
    const handlePageChange = val => {
      paginationProps.current = val;
      pager.pageNum = val;
      getRoleList();
    };
    const handleSizeChange = val => {
      paginationProps.pageSize = val;
      pager.pageSize = val;
      getRoleList();
    };

    // 设置权限
    const treeRef = ref();
    const treeData = ref([]);
    const checkedKeys = ref([]);
    const halfCheckedKeys = ref([]);
    const permissionsModalVisible = ref(false);
    const roleName = ref("");
    const roleId = ref("");
    const getMenuList = async () => {
      // 处理删除 tree 的 data 属性赋值, 否则不能绑定 data
      const deleteMap = list => {
        list.map(item => {
          delete item.icon;
          if (item.children) {
            deleteMap(item.children);
          }
        });
      };
      const { data } = await menuList();
      deleteMap(data.data);
      treeData.value = data.data;
    };
    const openPermissionModal = record => {
      roleName.value = record.roleName;
      roleId.value = record._id;
      treeRef.value.expandAll(true);
      permissionsModalVisible.value = true;
      const { checkedKeys } = record.permissionList;
      treeRef.value.checkNode(checkedKeys);
    };
    const handlePermissions = async () => {
      treeRef.value.getHalfCheckedNodes().map(item => {
        halfCheckedKeys.value.push(item._id);
      });
      let params = {
        _id: roleId.value,
        permissionList: {
          checkedKeys: checkedKeys.value,
          halfCheckedKeys: halfCheckedKeys.value
        }
      };
      const { data } = await rolePermission(params);
      console.log(data);
      permissionsModalVisible.value = false;
      window.location.reload();
    };
    const closePermissonsModal = () => {
      treeRef.value.checkAll(false);
      permissionsModalVisible.value = false;
    };

    // 删除
    const handleDelete = record => {
      Modal.warning({
        title: "警告",
        content: "此操作将停用该用户，是否继续！",
        hideCancel: false,
        onOk: async () => {
          const { data } = await roleDelete({
            _id: record._id
          });
          console.log(data);
          getRoleList();
        }
      });
    };
    return {
      queryForm,
      handleReset,
      queryFormRef,
      modalVisible,
      modalForm,
      action,
      modalFormRules,
      tableData,
      pager,
      paginationProps,
      handlePageChange,
      handleSizeChange,
      getRoleList,
      handleQuery,
      openAddModal,
      closeAddModal,
      handleAddOrUpt,
      modalFormRef,
      openUptModal,
      openPermissionModal,
      treeRef,
      halfCheckedKeys,
      treeData,
      roleName,
      roleId,
      checkedKeys,
      permissionsModalVisible,
      closePermissonsModal,
      handlePermissions,
      getMenuList,
      handleDelete
    };
  }
};
</script>

<style lang="scss" scoped>
</style>